CXX = @CXX@
CPPFLAGS = @CPPFLAGS@
CPPFLAGS_EXTRA = -DPKGVERSION="\"@PKGVERSION@\"" \
		 -DREPORT_BUGS_TO="\"@REPORT_BUGS_TO@\""
DEFS = @DEFS@
CPPFLAGS_ALL = $(DEFS) $(CPPFLAGS) $(CPPFLAGS_EXTRA)
CXXFLAGS = @CXXFLAGS@
LDFLAGS = @LDFLAGS@
LIBS = @LIBS@

CUDA_DRIVER_CPPFLAGS = @CUDA_DRIVER_CPPFLAGS@
CUDA_DRIVER_LDFLAGS = @CUDA_DRIVER_LDFLAGS@
CUDA_DRIVER_LDFLAGS_ALLOW_SHLIB_UNDEFINED = @CUDA_DRIVER_LDFLAGS_ALLOW_SHLIB_UNDEFINED@

AR = @AR@
RANLIB = @RANLIB@

LN_S = @LN_S@
INSTALL = @INSTALL@
INSTALL_DATA = @INSTALL_DATA@
INSTALL_PROGRAM = @INSTALL_PROGRAM@

prefix = @prefix@
exec_prefix = @exec_prefix@
bindir = @bindir@
libdir = @libdir@
srcdir = @srcdir@

mkinstalldirs = $(SHELL) $(srcdir)/mkinstalldirs

PROGRAMS = nvptx-none-as nvptx-none-ld @NVPTX_RUN@

all: $(PROGRAMS)

libiberty.stmp:
	cd libiberty/ && $(MAKE)
	: > $@

nvptx-none-as: $(srcdir)/nvptx-as.c libiberty.stmp $(srcdir)/version.h
	$(CXX) $(CPPFLAGS_ALL) $(CXXFLAGS) -I$(srcdir)/include \
		$< -o $@ \
		-Llibiberty -liberty $(LDFLAGS) $(LIBS)

nvptx-none-ld: $(srcdir)/nvptx-ld.c libiberty.stmp $(srcdir)/version.h
	$(CXX) $(CPPFLAGS_ALL) $(CXXFLAGS) -I$(srcdir)/include \
		$< -o $@ \
		-Llibiberty -liberty $(LDFLAGS) $(LIBS)

nvptx-none-run: $(srcdir)/nvptx-run.c libiberty.stmp $(srcdir)/version.h
	$(CXX) $(CUDA_DRIVER_CPPFLAGS) \
		$(CPPFLAGS_ALL) $(CXXFLAGS) -I$(srcdir)/include \
		$< -o $@ \
		$(CUDA_DRIVER_LDFLAGS) \
		-Llibiberty -liberty $(LDFLAGS) $(LIBS) \
		-lcuda $(CUDA_DRIVER_LDFLAGS_ALLOW_SHLIB_UNDEFINED)

.PHONY: install
install: all
	$(mkinstalldirs) $(DESTDIR)$(bindir)
	for x in $(PROGRAMS); do \
		$(INSTALL_PROGRAM) -m 755 $$x $(DESTDIR)$(bindir)/$$x; \
	done
	[ -z "@NVPTX_RUN@" ] || $(INSTALL_PROGRAM) -m 755 $(srcdir)/nvptx-run-single $(DESTDIR)$(bindir)/nvptx-none-run-single
	rm -f $(DESTDIR)$(bindir)/nvptx-none-ar
	rm -f $(DESTDIR)$(bindir)/nvptx-none-ranlib
	$(LN_S) $(AR) $(DESTDIR)$(bindir)/nvptx-none-ar
	$(LN_S) $(RANLIB) $(DESTDIR)$(bindir)/nvptx-none-ranlib
	$(mkinstalldirs) $(DESTDIR)$(prefix)/nvptx-none
	$(mkinstalldirs) $(DESTDIR)$(prefix)/nvptx-none/bin
	rel=$$(perl -MFile::Spec -e 'print File::Spec->abs2rel(@ARGV)' \
	  $(DESTDIR)$(bindir) $(DESTDIR)$(prefix)/nvptx-none/bin) && \
	for p in ar as ld ranlib; do \
	  rm -f $(DESTDIR)$(prefix)/nvptx-none/bin/"$$p" && \
	  $(LN_S) "$$rel"/nvptx-none-"$$p" $(DESTDIR)$(prefix)/nvptx-none/bin/"$$p"; \
	done
